package factory.one.controller;

import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * @author sk.z
 * 2023/10/7
 * 文件
 **/
@RequestMapping("/file")
@Controller
public class FileController {

    private final String PROPERTY_DIR_NAME = "user.dir";
    private final String ROOT = "files";
    private final int SLOT_SIZE = 255;

    private String rootPath;

    @ResponseBody
    @PostMapping(value = "/upload")
    public String upload(MultipartFile file, Long orderId) throws IOException {
        file.transferTo(new File(getOrderDir(orderId) + File.separator + file.getOriginalFilename()));
        return "ok";
    }

    @GetMapping(value = "/img/{orderId}/{fileName}")
    public void img(@PathVariable Long orderId,
                    @PathVariable String fileName,
                    HttpServletResponse response) {
        response.setHeader("Content-Type", "image/" + getContentType(fileName));
        File file = new File(getOrderDir(orderId) + File.separator + fileName);
        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
            Streams.copy(inputStream, response.getOutputStream(), true);
        } catch (IOException ignored) {
        }
    }

    public File[] getFiles(Long orderId) {
        File dir = new File(getOrderDir(orderId));
        if (dir.exists()) {
            return dir.listFiles();
        }
        return null;
    }

    private String getOrderDir(Long orderId) {
        long slot = orderId % SLOT_SIZE;
        String result = getRootPath() + File.separator + slot + File.separator + orderId;
        File dir = new File(result);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return result;
    }

    private String getRootPath() {
        if (rootPath == null) {
            String home = System.getProperty(PROPERTY_DIR_NAME);
            rootPath = home + File.separator + ROOT;
        }
        return rootPath;
    }

    private String getContentType(String fileName) {
        int i = fileName.lastIndexOf(".");
        if (i < 0) {
            return "jpeg";
        }
        String extend = fileName.substring(i);
        switch (extend.trim().toLowerCase()) {
            case "icon":
                return "x-icon";
            case "png":
                return "png";
            case "gif":
                return "gif";
            default:
                return "jpeg";
        }
    }

}
